#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

#include "./../../inc/homepage.h"
#include "./../../inc/msg_popup.h"
#include "./../../inc/user_event.h"

#define ULGRAY 0xF5F5F5
#define LDWHITE 0xF6F6F6
// #define LDWHITE 0xFDFDFD
lv_obj_t * chat_window                = NULL;
static lv_coord_t total_bubble_height = 0;

static void show_user_card_event_cb(lv_event_t * e);
static void chat_bubble_delete_event_cb(lv_event_t * e);

// 初始化聊天窗口
void chat_window_init(lv_obj_t * parent)
{
    if(chat_window != NULL) {
        total_bubble_height = 0;
        return;
    }

    chat_window = lv_obj_create(parent);
    lv_obj_set_style_bg_color(chat_window, lv_color_hex(LDWHITE), 0);
    if(user_event.chat_kb_open_status == 1)
        lv_obj_set_height(chat_window, LV_PCT(30));
    else
        lv_obj_set_size(chat_window, LV_PCT(100), LV_PCT(80));
    lv_obj_set_pos(chat_window, 0, LV_PCT(10));
    lv_obj_set_style_radius(chat_window, 0, 0);
    lv_obj_set_style_border_width(chat_window, 0, 0);
    lv_obj_set_style_pad_all(chat_window, 0, 0);

    total_bubble_height = 0;
}

// 自己发的气泡框
void selfChatBubble(lv_obj_t * parent, const char * msg)
{
    //  主容器
    lv_obj_t * selfBubble = lv_obj_create(parent);
    lv_obj_remove_style_all(selfBubble); // 清除所有样式（实现透明）
    lv_obj_set_style_pad_all(selfBubble, 5, 0);
    lv_obj_set_width(selfBubble, LV_PCT(100));
    lv_obj_set_height(selfBubble, LV_SIZE_CONTENT);
    lv_obj_clear_flag(selfBubble, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_set_y(selfBubble, total_bubble_height);

    // 头像（右侧）
    lv_obj_t * selfAvatar = lv_obj_create(selfBubble);
    lv_obj_set_size(selfAvatar, 40, 40);
    lv_obj_set_style_radius(selfAvatar, 2, 0);
    lv_obj_set_style_bg_color(selfAvatar, lv_color_hex(0xAAAAAA), 0);
    lv_obj_set_style_border_width(selfAvatar, 0, 0);
    lv_obj_align(selfAvatar, LV_ALIGN_TOP_RIGHT, -10, 0);

    // 内容区域   (气泡)
    lv_obj_t * contentArea = lv_obj_create(selfBubble);
    lv_obj_remove_style_all(contentArea);
    lv_obj_set_width(contentArea, LV_PCT(80));
    lv_obj_set_height(contentArea, LV_SIZE_CONTENT);
    lv_obj_set_style_pad_all(contentArea, 0, 0);
    lv_obj_align(contentArea, LV_ALIGN_TOP_RIGHT, -60, 0);
    lv_obj_clear_flag(contentArea, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    //  气泡框
    lv_obj_t * bubble = lv_obj_create(contentArea);
    lv_obj_set_style_bg_color(bubble, lv_color_hex(GRAY), 0);
    lv_obj_set_style_radius(bubble, 9, 0);
    lv_obj_set_style_pad_all(bubble, 8, 0);
    lv_obj_set_style_border_width(bubble, 0, 0);
    lv_obj_align(bubble, LV_ALIGN_TOP_RIGHT, 0, 0);
    lv_obj_clear_flag(bubble, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_set_height(bubble, LV_SIZE_CONTENT);

    // 气泡内容
    lv_obj_t * bubbleText = lv_label_create(bubble);
    lv_label_set_text(bubbleText, msg);
    lv_label_set_long_mode(bubbleText, LV_LABEL_LONG_WRAP);
    lv_obj_set_width(bubbleText, LV_PCT(100));
    lv_obj_set_style_text_font(bubbleText, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(bubbleText, lv_color_hex(WHITE), 0);

    // 让气泡框根据文本内容调整大小
    lv_obj_update_layout(bubbleText); // 更新文本布局
    // lv_obj_set_width(bubble, LV_SIZE_CONTENT);  // 宽度适应内容
    // lv_obj_set_height(bubble, LV_SIZE_CONTENT); // 高度适应内容

    total_bubble_height += lv_obj_get_height(selfBubble);
}

// 对方的聊天气泡框
void otherChatBubble(lv_obj_t * parent, const char * msg, const char * name)
{
    // 入参校验：避免name为空导致后续操作异常
    if(name == NULL || strlen(name) == 0) {
        printf("otherChatBubble: name为空，无法创建聊天气泡\n");
        return;
    }

    // 为name分配堆内存（关键修复：延长字符串生命周期，避免栈内存释放）
    char * name_copy = (char *)malloc(strlen(name) + 1);
    if(name_copy == NULL) {
        printf("otherChatBubble: 内存分配失败（name_copy）\n");
        return;
    }
    strcpy(name_copy, name);

    lv_obj_t * otherBubble = lv_obj_create(parent);
    lv_obj_remove_style_all(otherBubble); // 清除所有样式（实现透明）
    lv_obj_set_style_pad_all(otherBubble, 5, 0);
    lv_obj_set_width(otherBubble, LV_PCT(100));
    lv_obj_set_height(otherBubble, LV_SIZE_CONTENT);
    lv_obj_clear_flag(otherBubble, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_set_y(otherBubble, total_bubble_height);

    // 存储name_copy到气泡框的user_data，便于删除时释放内存
    lv_obj_set_user_data(otherBubble, name_copy);
    // 新增：气泡框删除时释放name_copy，避免内存泄漏
    lv_obj_add_event_cb(otherBubble, chat_bubble_delete_event_cb, LV_EVENT_DELETE, NULL);

    //  头像
    lv_obj_t * otherAvatar = lv_obj_create(otherBubble);
    lv_obj_set_size(otherAvatar, 40, 40);
    lv_obj_set_style_radius(otherAvatar, 2, 0);
    lv_obj_set_style_bg_color(otherAvatar, lv_color_hex(0xCCCCCC), 0);
    lv_obj_set_style_border_width(otherAvatar, 0, 0);
    lv_obj_align(otherAvatar, LV_ALIGN_TOP_LEFT, 10, 0); // 左中对齐

    //  内容区域（名字 + 气泡）
    lv_obj_t * contentArea = lv_obj_create(otherBubble);
    lv_obj_remove_style_all(contentArea);
    lv_obj_set_width(contentArea, LV_PCT(80));
    lv_obj_set_height(contentArea, LV_SIZE_CONTENT);
    lv_obj_set_style_pad_all(contentArea, 0, 0);
    lv_obj_align(contentArea, LV_ALIGN_TOP_LEFT, 60, 0);
    lv_obj_clear_flag(contentArea, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动

    // 名字（左对齐）
    lv_obj_t * otherName = lv_label_create(contentArea);
    lv_label_set_text(otherName, name); // 此处用原name，函数执行中内存有效
    lv_obj_set_style_text_font(otherName, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(otherName, lv_color_hex(BLACK), 0);
    lv_obj_align(otherName, LV_ALIGN_TOP_LEFT, 0, 0); // 名字在上

    // 气泡框
    lv_obj_t * bubble = lv_obj_create(contentArea);
    lv_obj_set_style_bg_color(bubble, lv_color_hex(WHITE), 0);
    lv_obj_set_style_radius(bubble, 9, 0);
    lv_obj_set_style_pad_all(bubble, 8, 0);
    lv_obj_set_style_border_width(bubble, 0, 0);
    lv_obj_align(bubble, LV_ALIGN_TOP_LEFT, 0, 25);
    lv_obj_clear_flag(bubble, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_set_height(bubble, LV_SIZE_CONTENT);

    // 气泡内容
    lv_obj_t * bubbleText = lv_label_create(bubble);
    lv_label_set_text(bubbleText, msg);
    lv_label_set_long_mode(bubbleText, LV_LABEL_LONG_WRAP);
    lv_obj_set_width(bubbleText, LV_PCT(100));
    lv_obj_set_style_text_font(bubbleText, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(bubbleText, lv_color_hex(BLACK), 0);

    lv_obj_update_layout(otherBubble); // 更新文本布局
    // lv_obj_set_width(bubble, LV_SIZE_CONTENT);  // 宽度适应内容
    // lv_obj_set_height(bubble, LV_SIZE_CONTENT); // 高度适应内容

    total_bubble_height += lv_obj_get_height(otherBubble);

    // 修复：绑定堆内存name_copy到事件回调，而非栈上的name
    lv_obj_add_event_cb(otherAvatar, show_user_card_event_cb, LV_EVENT_CLICKED, name_copy);
}

// 显示聊天室加入/退出信息
void show_chatroom_join_exit_tag(lv_obj_t * parent, const char * msg)
{

    lv_obj_t * chat_room_box_join_exit_tag = lv_obj_create(parent);
    lv_obj_remove_style_all(chat_room_box_join_exit_tag); // 清除所有样式（实现透明）
    lv_obj_set_style_pad_all(chat_room_box_join_exit_tag, 5, 0);
    lv_obj_set_size(chat_room_box_join_exit_tag, LV_PCT(100), 30);
    lv_obj_clear_flag(chat_room_box_join_exit_tag, LV_OBJ_FLAG_SCROLLABLE); // 不可滚动
    lv_obj_set_y(chat_room_box_join_exit_tag, total_bubble_height);

    lv_obj_t * title = lv_label_create(chat_room_box_join_exit_tag);
    lv_obj_set_style_text_font(title, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
    lv_obj_set_style_text_color(title, lv_color_hex(BLACK), 0);
    lv_obj_center(title);

    lv_label_set_text(title, msg);

    lv_obj_update_layout(chat_room_box_join_exit_tag); // 更新文本布局

    total_bubble_height += lv_obj_get_height(chat_room_box_join_exit_tag);
}

static void show_user_card_event_cb(lv_event_t * e)
{
    // 获取堆内存中的name，避免野指针
    char * name = (char *)lv_event_get_user_data(e);
    // 校验name有效性，避免空指针访问
    if(name == NULL || strlen(name) == 0) {
        printf("show_user_card_event_cb: name无效，无法显示用户卡片\n");
        return;
    }
    show_user_card(home_src, name);
}

// 聊天气泡删除时释放name_copy内存，避免内存泄漏
static void chat_bubble_delete_event_cb(lv_event_t * e)
{
    lv_obj_t * otherBubble = lv_event_get_target(e);
    if(otherBubble == NULL) return;

    // 获取并释放堆内存中的name_copy
    char * name_copy = (char *)lv_obj_get_user_data(otherBubble);
    if(name_copy != NULL) {
        free(name_copy);
        lv_obj_set_user_data(otherBubble, NULL); // 置空，避免重复释放
        // printf("chat_bubble_delete_event_cb: 释放name_copy内存：%p\n", name_copy);
    }
}